//
//  FirmwareResetController.swift
//  DaRings
//
//  Created by 易先生 on 2022/10/31.
//

import UIKit
import MYModule
import CRPSmartRing


open class FirmwareResetController: BaseViewController {
    
    private var timer: Timer?

    open override func viewDidLoad() {
        super.viewDidLoad()
        
        BluetoothManager.shared.resetDevice()
        
    }
    
    open override func makeUI() {
        super.makeUI()
        
        view.backgroundColor =  UIColor.darkBackground
        view.addSubview(titleView)
        view.addSubview(resetStackView)
        resetStackView.addArrangedSubview(iconImage)
        resetStackView.addArrangedSubview(descLabel)

        titleView.snp.makeConstraints { make in
            make.top.equalTo(topLayoutGuide.snp.bottom)
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
        }
        
        resetStackView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
    }
    
    open override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.removeTimer()
    }
    
    open override func bindViewModel() {
        super.bindViewModel()
        
        self.viewModel.items.subscribe(onNext: { [weak self] isCompleted in
            guard let self = self else { return }
            if isCompleted {
                self.descLabel.text = "firmware_reset_succed_title".language
            }
        }).disposed(by: rx.disposeBag)
        
        // 如果断开连接，那么30S内没连上，需要弹窗，如果30S内连上了，也弹窗，提示成功
        NotificationCenter.default.rx.notification(Notification.Name.kDeviceStateNotification).take(until: self.rx.deallocated).subscribe(onNext:{[weak self] notification in
            guard let self = self else { return }
            guard let result = notification.userInfo as? [String: Any] else { return}
            guard let state = result["result"] as? CRPState else { return }
            guard state != .connected else {
                UIAlertController.showOkAlert(title: "firmware_reset_succed_title".language, message: "", in: self) {
                    self.navigationController?.popViewController(animated: true)
                }
                self.removeTimer()
                return
            }
            
            self.addTimer()

        }).disposed(by: rx.disposeBag)


        NotificationCenter.default.rx.notification(Notification.Name.kBluetoothStateNotification).take(until: self.rx.deallocated).subscribe(onNext:{[weak self] notification in
            guard let self = self else { return }
            guard let result = notification.userInfo as? [String: Any] else { return}
            guard let state = result["result"] as? CRPBluetoothState else { return }
            switch state{
            case .poweredOff:
                UIAlertController.showOkAlert(title: "dialog_firmware_reset_ble_powered_off_patiently".language, message: "", in: self) {
                    self.navigationController?.popViewController(animated: true)
                }
                self.removeTimer()
                break
                
            case .poweredOn:
                self.removeTimer()
                self.addTimer()
                
                break


            default:
                break
            }


        }).disposed(by: rx.disposeBag)

    }
    
    //MARK: - 定时器
    private func addTimer() {
        log.debug("设置定时器")

        if self.timer == nil {
            self.timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true, block: {[weak self] _ in
                guard let self = self else { return }
                //
                UIAlertController.showOkAlert(title: "".language, message: "dialog_firmware_reset_ble_powered_off_patiently".language, in: self) {
                    self.navigationController?.popViewController(animated: true)
                }
                self.removeTimer()

            })
        }
        
        RunLoop.current.add(self.timer!, forMode: .common)
    }

    private func removeTimer() {
        if self.timer != nil {
            self.timer?.invalidate()
            self.timer = nil
        }
    }
    
    //MARK: - 返回按钮事件
    open override func backAction() {
        UIAlertController.showAlertOk(title: "".language, message: "dialog_firmware_reset_wait_patiently".language, in: self)
        return
    }
    
    //MARK: - lazy load -

    private lazy var titleView: TopTitleView = {
        let titleView = TopTitleView()
        titleView.configTitle(title: "other_settings_factory_reset".language)
        return titleView
    }()
    
    
    private lazy var resetStackView: StackView = {
        let resetStackView = StackView()
        resetStackView.axis = .vertical
        resetStackView.spacing = 38
        resetStackView.alignment = .center
        return resetStackView
    }()
    
    private lazy var iconImage: ImageView = {
        let iconImage = ImageView()
        iconImage.image = UIImage(named: "ic_user_firmware_upgrade_checking")
        return iconImage
    }()
    
    private lazy var descLabel: Label = {
        let descLabel = Label()
        descLabel.textColor = UIColor.assist_222222
        descLabel.numberOfLines = 0
        descLabel.text = "firmware_reset_center_title".language
        descLabel.font = Fonts.systemFont(ofSize: 16)
        return descLabel
    }()
    
    private lazy var viewModel: FirmwareResetViewModel = {
        let viewModel = FirmwareResetViewModel()
        return viewModel
    }()
    
}
